<?php
/**
 * @copyright (C) veapon.com
 * @file Upload.class.php
 * @brief 上传类
 * @author veapon 
 * @version v1.0
 * @date 2012-03-30
 */
class Upload{
	private $file 	= "";
	private $error 	= false; 
	private $errMsg	= array(
				'illegal_op'	=> '非法上传',
				'size_error'	=> '文件大小超过限制',
				'type_error'	=> '文件类型不允许上传',
				'override_error'=> '已存在同名文件',
				'make_dir_error'=> '创建保存目录失败',
			); 
	public $cfg 	= array(
				'max_size'	=> 0,
				'safe_ext'	=> array('jpg','png','gif','txt','doc','docx','ppt','pptx','xls','xlsx','pdf','rar','zip','7z'),
				'override'	=> true,
				'save_path'	=> './',
			);
	public $saveName;


	public function __construct($field="file", $config=""){
		$this->file = $_FILES[$field];
		if( is_array($config) ) $this->cfg = array_merge($this->cfg,$config);
	}
	
	private function valid(){
		if( !is_uploaded_file($this->file['tmp_name']) ){
			$this->error = $this->errMsg['illegal_op'];
			return false;
		}
		if( $this->cfg['safe_ext'] && count($this->cfg['safe_ext'])>0 && !in_array($this->get_pro('ext'),$this->cfg['safe_ext']) ){
			$this->error = $this->errMsg['type_error'];
			return false;
		}
		if( !empty($this->cfg['max_size']) && ($this->get_pro('size')>$this->cfg['max_size']) ){
			$this->error = $this->errMsg['size_error'];
			return false;
		}
		if( file_exists($this->cfg['save_path'].$this->saveName) && !$this->cfg['override'] ){
			$this->error = $this->errMsg['override_error'];
			return false;
		}
		return true;
	}

	private function create_folder($path, $mode=0755) { 
		if (!file_exists($path)) { 
			$this->create_folder(dirname($path)); 
			@mkdir($path, $mode); 
		} 
	} 

	public function save($file_name=""){
		$this->saveName = empty($file_name) ? $this->file['name'] : $file_name.'.'.$this->get_pro('ext');
		if( $this->valid() ){
			if( !empty($this->cfg['save_path']) && $this->cfg['save_path'] != './' && !is_dir($this->cfg['save_path']) ){
				$this->create_folder($this->cfg['save_path']);
			}
			$file = ltrim($this->cfg['save_path'],DS).DS.$this->saveName;
			return @move_uploaded_file($this->file['tmp_name'],$file);
		}else{
			return false;
		}
	}

	public function get_pro($item){
		switch($item){
			case "ext":
				$fileName = $this->file['name'];
				$filter = explode(".",$fileName);
				return strtolower($filter[count($filter)-1]);
			break;
			case "size":
				return $this->file['size'];
			break;
			default:
				return false;
			break;
		}
	}

	public function get($param){
		if( isset($this->$param) ) return $this->$param;
	}

	public function config($array){
		if( is_array($array) && count(array_diff_key($array,$this->cfg))==0 ){
			$this->cfg = array_merge($this->cfg,$array);
		}
	}
}
